var normalizeValue = 10;
var maximumScore = 0;

function init() {
	if (wave && wave.isInWaveContainer()) {
		wave.setStateCallback(stateChanged);
		wave.setParticipantCallback(stateChanged);
	}
}

function stateChanged() {
	if (!wave.getState()) {
		return;
	}
	var participants = getInterestingParticipants();
	if (participants) {
		var needNormalize = 0;
		for (var i = 0; i < participants.length; ++i) {
			var participant = participants[i];
			var element = "._" + i;
			var margin_left = 110 + (participants[i]["score"] / normalizeValue);
			if (participants[i]["score"] > maximumScore) { maximumScore = participants[i]["score"]; }
			$(element).children("img").attr({id : participants[i]["name"], src : participants[i]["thumb"]});
			$(element).children("div.user_label").children("span.score").text(participants[i]["score"]);
			$(element).children("img").animate({marginLeft: margin_left }, 100);
			$(element).children("div.user_label").children("span.participate_button").children("button").attr({id : participants[i]["name"]});

			if (participant["playing"] == "1") {
				$(element).children("div.user_label").children("span.participate_button").children("button.participate_button").hide();
				$(element).children("div.user_label").children("span.participate_button").children("span.participate_text").show();
				$(element).children("div.user_label").children("span.participate_button").children("span.participate_text").html("<img src='http://gamewave.googlecode.com/svn/trunk/images/icons/joined.png' style='width: 20px; height: 20px;' />");
			} else if (participant["playing"] == "0") {
				if (getGamerId(wave.getViewer()) != participants[i]["name"]) {
					$(element).children("div.user_label").children("span.participate_button").children("button.participate_button").hide();
					$(element).children("div.user_label").children("span.participate_button").children("span.participate_text").show();
					$(element).children("div.user_label").children("span.participate_button").children("span.participate_text").html("<img src='http://gamewave.googlecode.com/svn/trunk/images/icons/not_joined.png' style='width: 20px; height: 20px;' />");
				} else {
					$(element).children("div.user_label").children("span.participate_button").children("span.participate_text").hide();
					$(element).children("div.user_label").children("span.participate_button").children("button.participate_button").show();
				}
			}
		} // end for
		normalizeValue = 10 * (1 + Math.floor(maximumScore / 5000));
	} // end if	participants
} // end function state Changed

var gameStarted = false;
function getInterestingParticipants() {
	var participants = wave.getParticipants();
	var ips = new Array(participants.length);
	var readyPlayers = 0;
	var score;
	for (var i = 0; i < participants.length; ++i) {
		var ip = {};
		ip["name"] = getGamerId(participants[i]);
		ip["thumb"] = participants[i].getThumbnailUrl();
		ip["score"] = parseInt(wave.getState().get(getGamerId(participants[i]), "0"));
		ip["playing"] = wave.getState().get(getGamerId(participants[i]) + "_playing", "0");
		if (ip["playing"] == "1") readyPlayers++;
		ips[i] = ip;
	} // end for
	//debugPrint("Ready: " + readyPlayers + " Total: " + participants.length);
	if (readyPlayers == 0) gameStarted = false;
	if (readyPlayers == participants.length) { if (!gameStarted) startCountdown(); gameStarted = true; }
	ips.sort(sortByScore);
	if (ips.length <= 3) {
		return ips;
	} else {
	   for (var i = 0; i < ips.length; ++i) {
	   	if (ips[i]["name"] == getGamerId(wave.getViewer())) {
				switch(i) {
					case 0:
						return ips.slice(0, 2);
					case ips.length:
						return ips.slice(ips.length-2);
					default:
						return ips.slice(i-1, i+1);
				} // end switch
			} // end if
	   } // end for
	}
}

function sortByScore(a, b) {
    var x = a["score"];
    var y = b["score"];
    return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}

function getGamerId(participant) {
	return participant.getId().split("@")[0];
}

function updateScore(points) {
	var gamerId = getGamerId(wave.getViewer());
	delta = {};
   delta[gamerId] = points;
	wave.getState().submitDelta(delta);
}

function updateMood() {
	delta = {};
   delta[getGamerId(wave.getViewer()) + "_playing"] = "1";
	wave.getState().submitDelta(delta);
}

function updateMoodOver() {
	delta = {};
   delta[getGamerId(wave.getViewer()) + "_playing"] = "0";
	wave.getState().submitDelta(delta);
}

var debugLines = 0;
function debugPrint(msg) {
	if (++debugLines % 5 == 0) {
		$("div.debug").html("");
	}
	$("div.debug").append(msg + "<br>");
}

$("document").ready(function () {
	$("button.participate_button").click(function () {
		updateMood();
	});
	normalizeValue = 10;
	maximumScore = 0;
});

gadgets.util.registerOnLoadHandler(init);


